﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using YYTea.MOdel.Model;
using YYTea.ORM;
using YYTea.Services.IServices;
using YYTea.Services.VModel;

namespace YYTea.Miljy.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IConfiguration _configration;
        private readonly UserManager<UserInfo> _userManager;
        private readonly SignInManager<UserInfo> _signInManager;
        //private readonly RoleManager<UserRole> _roleManager;
        private readonly YYTeaContext _context;
        private readonly IShoppingCar _shoppingCar;


        public AuthenticationController(
            IConfiguration configuration,
            UserManager<UserInfo> userManager,
            SignInManager<UserInfo> signInManager,
            //RoleManager<UserRole> roleManager,
            YYTeaContext context,
            IShoppingCar shoppingCar


            )
        {
            this._configration = configuration;
            this._userManager = userManager;
            this._signInManager = signInManager;
            //this._roleManager = roleManager;
            this._context = context;
            _shoppingCar = shoppingCar;

        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] UserLogin login)
        {

            // 1.验证用户
            var loginResult = await _signInManager.PasswordSignInAsync(
                login.UserName,
                login.Password,
                //多次登录
                false,
                //是否锁定
                false
                );
            if (!loginResult.Succeeded)
            {
                return BadRequest("用户名或者密码错误,请重新输入");
            }
            var user = await _userManager.FindByNameAsync(login.UserName);

            // 2.创建jwt
            //herder
            var signitureAlgorithm = SecurityAlgorithms.HmacSha256;
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub,user.Id)
             };
            //获取用户角色
            var roleNames = await _userManager.GetRolesAsync(user);
            foreach (var roleName in roleNames)
            {
                var roleClaim = new Claim(ClaimTypes.Role, roleName);
                claims.Add(roleClaim);
            }
            //signiture
            var secreyByte = Encoding.UTF8.GetBytes(_configration["Authentication:SecreyKey"]);
            var secerykey = new SymmetricSecurityKey(secreyByte);
            var signingCredentials = new SigningCredentials(secerykey, signitureAlgorithm);

            var token = new JwtSecurityToken(
                issuer: _configration["Authentication:Issuer"],
                audience: _configration["Authentication:Audience"],
                claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(1)
                );
            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

            return Ok(tokenStr);

        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Register([FromBody] UserRegister register)
        {
            // 1.使用用户对象
            var user = new UserInfo()
            {
                UserName = register.UserName,
                Email = register.UserName,
                //RoleName = r.Name = "普通用户",
                AddTime = DateTime.Now,
                PhoneNumber = register.PhoneNumber,
                EmailConfirmed = true,
                Image = "/Img/头像.png"

            };
            //唯一电话号码
            var userph = _context.UserInfos.SingleOrDefault(s => s.PhoneNumber == register.PhoneNumber);
            if (userph != null)
            {
                return BadRequest("此电话号码的用户已存在");
            }
            var userEmail = _context.UserInfos.SingleOrDefault(s => s.Email == register.UserName);
            if (userEmail != null)
            {
                return BadRequest("该用户已存在");
            }
            var userRole = new UserRole()
            {
                UserId = user.Id,
                RoleId = "3"
                
            };
            // 2.hash密码,创建用户
            var result = await _userManager.CreateAsync(user, register.Password);
            if (!result.Succeeded)
            {
                return BadRequest();
            }

            await _context.UserRole.AddAsync(userRole);
            await _context.SaveChangesAsync();

            // 3.初始化购物车
            var shoppingCar = new ShoppingCarVModel()
            {
                //UserId = user.Id,
                //DateTime = DateTime.Now,

            };
            await _shoppingCar.AddShoppingCar(shoppingCar, user.Id);

            // 4
            return Ok();
        }


        //[HttpDelete]
        //public async Task<IActionResult> Logout()
        //{
        //    await _signInManager.SignOutAsync();
        //    return RedirectToAction();
        //}

    }
}
